import {
	ref,
	computed,
	defineExpose
} from 'vue'
import {
	onReady,
	onNavigationBarButtonTap,
	onShow,
	onLoad,
	onPullDownRefresh,
	onReachBottom
} from '@dcloudio/uni-app'
import {
	getAction,
	postAction,
	postFormAction,
	httpAction,
	deleteAction
} from '@/utils/request.js';
import {
	Toast
} from '@/utils/commonHeader.js';
import {
	filterObj
} from '@/utils/util.js';
import {
	useStore
} from 'vuex'

export const useList = (options = {}) => {
	const store = useStore()
	const {
		linkUrls,
		detailUrls,
		url = {},
		afterSearch = () => {},
		isOnShow = true
	} = options
	console.log("useList-options", options)
	const checkAll = ref(false)
	const list = ref([])
	const page = ref(options.pagepage || 1)
	const pageSize = ref(options.pageSize || 20)
	const totals = ref(options.totals || 0)
	const isorter = ref(options.isorter || {
		// orderBy: 'createTime',
		sort: 'desc',
	})
	const isDoRefresh = ref(false)
	const isRefresh = ref(false)
	const queryParam = ref(options.queryParam || {})
	const isNull = ref(false)
	const loadHock = ref(options.loadHock || false)
	const isGet = ref(options.isGet == false ? false : true) //是否get请求
	const isOnReachBottom = ref(options.isOnReachBottom || true) //是否触底加载
	const resultList = ref([]) //已选
	const isResult = ref(options.isResult || false) //是否是result数据
	const pageSetup = ref([]) //列表块样式
	const cols = ref([]) //没有pageSetup时默认显示cols
	const conditions = ref([]) //查询条件
	const selectList = ref([]) //可下拉选择的查询数组
	const selectTime = ref([]) //可下拉选择的查询时间数据
	const canAdd = ref(options.canAdd || false)
	const canDel = ref(options.canDel || false)
	const canEdit = ref(options.canEdit || false)
	const moduleName = ref('')
	const isPostFormAction = ref(options.isPostFormAction || false) //是否表单传值
	const conditionsFilter = ref([]) // 下拉 文本 时间点 时间段 复选框 单选
	const fieldOptions = ref([]) //下拉。包括树
	const currentFilter = ref([]) //当前点击的条件对象
	const queryParamsFilter = ref({})
	const btnAddName = ref('新增')
	const btnEditName = ref('编辑')
	const btnDelName = ref('删除')
	const fileChildren = ref([]) //子级目录
	const files = ref([])


	const fenPage = computed(() => Math.ceil(totals.value / pageSize.value))




	//点击导航栏新增
	onNavigationBarButtonTap(() => {
		if (linkUrls) {
			uni.navigateTo({
				url: `${linkUrls}`
			});
		}
	})

	//数据调取结束后调用函数，自定义逻辑,在主页面实现
	const hadSearchData = (list, totals) => {
		afterSearch(list, totals)
	}
	/*获取list*/
	const getListData = async () => {
		console.log("isGet", isGet.value)
		try {
			if (!url.list) {
				uni.showToast({
					title: '请设置url.list',
					duration: 2000
				});
				return
			}
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			let params = filterObj({
				page: page.value,
				pageSize: pageSize.value,
				...isorter.value,
				...queryParam.value
			})
			console.log("params", params);
			if (isGet.value) {
				await getAction(url.list, params).then((res) => {
					console.log('getAction res', res);
					if (page.value == 1) {
						cols.value = []
						pageSetup.value = []
						list.value = []
						selectList.value = []
						conditions.value = []
						selectTime.value = []
						fileChildren.value = []
						clearConditionsFilter()
					}
					if (res.code == 200 || res.res == 0) {
						console.log("mixres", res);
						if (res.moduleName) {
							moduleName.value = res.moduleName;
							uni.setNavigationBarTitle({
								title: res.moduleName
							});
						}
						console.log("getListData->res", res)
						let results = res.result || res.data || {}
						console.log("getListData->results", results)
						fileChildren.value = results.children || []
						canAdd.value = results.canAdd ? results.canAdd : false
						canDel.value = results.canDel ? results.canDel : false
						canEdit.value = results.canEdit ? results.canEdit : false
						btnAddName.value = results.btnAddName ? results.btnAddName : btnAddName
							.value;
						btnEditName.value = results.btnEditName ? results.btnEditName : btnEditName
							.value;
						btnDelName.value = results.btnDelName ? results.btnDelName : btnDelName
							.value;
						files.value = results.files && Array.isArray(results.files) ? results
							.files : []
						conditions.value = results.conditions && Array.isArray(results.conditions) ?
							results
							.conditions : []

						handleConditionsFilter(conditions.value)
						if (conditions.value.length > 0) {
							selectList.value = conditions.value && Array.isArray(conditions
									.value) &&
								conditions.value.length > 0 ? conditions.value.filter(item => item
									.fieldType !=
									7 && item.fieldType != 8) : []
							selectTime.value = conditions.value && Array.isArray(conditions
									.value) &&
								conditions.value.length > 0 ? conditions.value.filter(item => item
									.fieldType ==
									7 || item.fieldType == 8) : []
						}
						let _cols = results.cols && Array.isArray(results.cols) ? results.cols : []
						let _pageSetup = results.pageSetup && Array.isArray(results.pageSetup) &&
							results
							.pageSetup.length > 0 ? results.pageSetup : []
						let arrs = results.datas && Array.isArray(results.datas) && results.datas
							.length >
							0 ? results.datas : [];
						if (results.list && results.list && Array.isArray(results.list)) {
							arrs = results.list
						}
						cols.value = [..._cols]
						pageSetup.value = [..._pageSetup]
						arrs.forEach(item => {
							item.show = false
						})
						totals.value = results.total;
						list.value = [...list.value, ...arrs]
						isNull.value = list.value && list.value.length > 0 ? false : true
						// this.$emit("update:selectList", this.selectList)
						// this.$emit("update:selectTime", this.selectTime)
						// this.$emit("update:list", this.list)

						if (pageSetup.value.length > 0) {
							list.value.forEach((item) => {
								// 去掉已在平铺视图中显示的button
								item.colOperateSwipeBtns = item.colOperateBtns.filter((
									btn) => {
									return pageSetup.value.some(el => !el.blocks
										.some(
											b => b
											.type === 'button' && b.btnName ==
											btn
											.name
										));
								})
							})
						}else{
							list.value.forEach((item) => {
								item.colOperateSwipeBtns = item.colOperateBtns || []
							})
						}
						console.log("list", {
							list: list.value,
							pageSetup: pageSetup.value,
							cols: cols.value,
							totals: totals.value,
							conditionsFilter: conditionsFilter.value
						})
						hadSearchData(list.value)
					} else {
						list.value = [];
						isNull.value = true
					}
				}).finally(() => {
					uni.hideLoading()
				}).catch(e => {
					console.log("getListData", e)
				})
			} else {
				let api = null
				if (isPostFormAction.value) {
					api = postFormAction
				} else {
					api = postAction
				}
				await api(url.list, params).then((res) => {
					if (page.value == 1) {
						cols.value = []
						pageSetup.value = []
						list.value = []
						selectList.value = []
						conditions.value = []
						selectTime.value = []
						clearConditionsFilter()
					}
					if (res.code == 200 || res.res == 0) {
						console.log("res", res);
						if (res.moduleName) {
							moduleName.value = res.moduleName;
							uni.setNavigationBarTitle({
								title: res.moduleName
							});
						}
						let arrs = res.data.list || [];
						arrs.forEach(item => {
							item.show = false
						})
						totals.value = res.data.total;
						list.value = [...list.value, ...arrs]
						hadSearchData(list.value)
						console.log("list.value", list.value)
					} else {
						list.value = [];
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				}).finally(() => {
					uni.hideLoading()
				})
			}
		} catch (error) {
			console.error('url.list', url.list);
			console.error("getListData", error)
		}
	}
	const search = () => {
		page.value = 1
		getListData()
	}
	onLoad((option) => {
		console.log("f-onLoad")
		let rows = option.infos
		//用户传递子id时候需要带入请求list里面
		if (rows) {
			const {
				key,
				id
			} = JSON.parse(rows)
			console.log(rows)
			queryParam.value[key] = id
		}
		loadHock.value && search();
	})
	//新增完之后刷页面
	onShow(() => {
		console.log("f-onShow")
		if (isDoRefresh.value == true) {
			currPage.isDoRefresh = false;
			list.value = []
			page.value = 1;
			getListData()
		}
		if (isOnShow) {
			if (isRefresh.value == false) {
				isRefresh.value = true;
			} else {
				search();
			}
		}
	})

	//下拉刷新
	onPullDownRefresh(() => {
		console.log('下拉');
		// #ifdef MP-WEIXIN
		search();
		wx.stopPullDownRefresh();
		// #endif


		// #ifdef APP-ANDROID  || H5 || APP-PLUS
		uni.startPullDownRefresh();
		search();
		uni.stopPullDownRefresh();
		// #endif

		// #ifdef APP-IOS || APP-HARMONY
		search();
		setTimeout(() => {
			uni.stopPullDownRefresh();
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 300
			}, 20);
		})
		// #endif
	})

	//上滑动刷新
	onReachBottom(() => {
		console.log('上滑首页');
		getOnReachBottom();
	})
	//触底加载
	const getOnReachBottom = () => {
		console.log('getOnReachBottom isOnReachBottom', isOnReachBottom.value);
		if (isOnReachBottom.value) {
			page.value++
			if (page.value > fenPage.value) {
				uni.showToast({
					title: '没有更多数据',
					duration: 2000
				});
				return false;
			} else {
				getListData();
			}
		}
	}
	//刷新当前页
	const getThisPage = async () => {
		list.value = []
		await getListData()
	}

	//重置条件
	const clearConditionsFilter = () => {
		conditionsFilter.value = []
	}
	//处理条件
	const handleConditionsFilter = () => {
		clearConditionsFilter()
		if (conditions.value && conditions.value.length) {
			conditionsFilter.value = conditions.value
			conditionsFilter.value.forEach(item => {
				if (!queryParamsFilter.value[item.fieldName]) {
					queryParamsFilter.value[item.fieldName] = ''
				}
				if (item.fieldOptions && typeof item.fieldOptions === 'string') {
					item.fieldOptions = JSON.parse(item.fieldOptions)
				}
				if (item.type == 'checkbox' || item.type == 'radio') {
					//查询时回显值
					if (item.fieldOptions && item.fieldOptions.length) {
						item.fieldOptions = item.fieldOptions.map(el => {
							el.text = el.name
							return {
								...el,
							}
						})
					} else {
						item.fieldOptions = []
					}
				}
			})
		}
		console.log("conditionsFilter.value", conditionsFilter.value)
		console.log("queryParamsFilter.value", queryParamsFilter.value)
	}

	const changeSelect = (e, index) => {
		let isCheck = e.target.value.length > 0
		//全选时候
		if (index < 0) {
			checkAll.value = isCheck
			//选中
			if (isCheck) {
				list.value.map(res => res.checked = true)
			} else {
				list.value.map(res => res.checked = false)
			}
			//取消
		} else {
			list.value[index].checked = isCheck
		}
	}
	//详情
	const showDetails = (data) => {
		uni.navigateTo({
			url: `${detailUrls}?record=${JSON.stringify(data)}`
		})
	}


	const deleteData = () => {
		uni.showModal({
			title: '确认删除选中项目',
			content: '点击确认删除数据',
			confirmColor: '#098af0',
			success: function(res) {
				if (res.confirm) {
					deleteComfirmed();
				} else if (res.cancel) {
					Toast('none', '已取消删除')
				}
			}
		});
	}
	//删除
	const deleteComfirmed = () => {
		//把所有 checked 是true的部找出来
		let DeleteDatas = list.value.filter(res => res.checked == true);
		if (DeleteDatas.length == 0) {
			Toast('none', "请选择要删除的数据")
			return;
		}
		list.value = list.value.filter(res => res.checked == false);
		//组合批量的id
		let ids = new Array()
		DeleteDatas.map(ret => ids.push(ret.id))
		//id数组转换成字符串拼接
		ids = String(ids)
		httpAction(`${url.delete}?ids=${ids}`, {}, 'delete').then(res => {
			if (res.success) {
				//成功掉接口
				resetData()
			}
			Toast('none', res.message)
		})
	}

	/*重置*/
	const resetData = () => {
		page.value = 1
		list.value = []
		totals.value = 0
		getListData()
	}
	const deleteOne = (id) => {
		deleteAction(url.delete, {
			id: id
		}).then((res) => {
			if (res.success) {
				uni.showToast({
					icon: "success",
					mask: true,
					title: res.message,
				});
				page.value = 1
				getThisPage();
			} else {
				uni.showToast({
					icon: "error",
					mask: true,
					title: res.message,
				});
			}
		});
	}

	return {
		checkAll,
		list,
		page,
		pageSize,
		totals,
		isorter,
		isDoRefresh,
		queryParam,
		isNull,
		loadHock,
		isGet,
		isOnReachBottom,
		resultList,
		isResult,
		pageSetup,
		cols,
		conditions,
		selectList,
		selectTime,
		canAdd,
		canDel,
		canEdit,
		moduleName,
		isPostFormAction,
		conditionsFilter,
		fieldOptions,
		currentFilter,
		queryParamsFilter,
		btnAddName,
		btnEditName,
		btnDelName,
		fileChildren,
		search,
		getListData,
		changeSelect,
		showDetails,
		deleteData,
		getOnReachBottom
	}

}


export const useExternalEmail = ({
	url,
	fetch,
	type:_type
}) => {
	const store = useStore()
	const emailInfo = computed(() => store.state.emailInfo)
	const isChecked = ref(false) //长按打开多选
	const type = ref(_type || '')
	const moveOptions = [{
			text: '发件箱',
			value: 3,
		},
		{
			text: '草稿箱',
			value: 0,
		},
		{
			text: '删除',
			value: 2,
		},
	]

	const readOptions = [{
			text: '已读',
			value: 1,
		},
		{
			text: '未读',
			value: 0,
		},
	]
	const {
		page,
		getListData,
		queryParam,
		list
	} = useList({
		queryParam: {
			action: 'search',
			what: '',
			emailId: emailInfo.value.id
		},
		url,
		isGet: false,
		isPostFormAction: true,
	})
	onLoad(() => {
		console.log("emailInfo.value", emailInfo.value)
		if (!emailInfo.value.id) {
			return
		}
		queryParam.value.emailId = emailInfo.value.id
		if (typeof fetch === 'function') {
			fetch()
		} else {
			search();
		}
	})

	function _handleRefresh() {
		search()
	}

	function search() {
		page.value = 1
		isChecked.value = false
		getListData();
	}

	function _handleLook(record) {
		uni.navigateTo({
			url: `/cmn/externalEmail/common/inboxView?${type.value}&mainId=${record.id}`,
		});
	}

	function _handleEdit(record) {
		uni.navigateTo({
			url: `/cmn/externalEmail/writebox/index?type=${type.value}&mainId=${record.id}`,
		});
	}
	//转发
	function _handleTransmit(record) {
		uni.navigateTo({
			url: `/cmn/externalEmail/writebox/index?type=transmit&mainId=${record.id}`,
		});
	}

	function _handleDelete(record) {
		uni.showModal({
			title: "提示",
			content: "您确定删除么？",
			success: (res) => {
				if (res.confirm) {
					handleDelete(record.id);
				} else if (res.cancel) {
					console.log("用户点击取消");
				}
			},
		});
	}
	//全选
	function _handleSelectAll() {
		list.value.forEach(item => {
			item.checked = true
		})
		list.value = [...list.value]
	}
	//取消全选
	function _handleCancel() {
		list.value.forEach(item => {
			item.checked = false
		})
		list.value = [...list.value]
		isChecked.value = false
	}
	//删除
	function handleDelete(ids) {
		try {
			uni.showLoading({
				title: '删除中',
				mask: true
			});
			postFormAction(url.delete, {
				ids: ids,
				emailId: queryParam.value.emailId
			}).then((res) => {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				});
				if (res.data.res == 0) {
					//删除后要刷新，确保list能够触底加载
					_handleRefresh();
				}
			});
		} catch (e) {
			uni.hideLoading()
		} finally {
			uni.hideLoading()
		}
	}
	//批量删除
	function _handleDeleteBatch() {
		let selectList = list.value.filter(item => item.checked);
		let checkes = selectList.map(item => item.id);
		if (checkes.length == 0) {
			uni.showToast({
				title: '请选择数据',
				icon: 'none'
			});
			return;
		}
		const ids = checkes.join(',');
		uni.showModal({
			title: "提示",
			content: "您确定删除么？",
			success: async (res) => {
				if (res.confirm) {
					handleDelete(ids)
				}
			}
		})
	}
	const showReadRef = ref(null)

	function handleShowRead() {
		showReadRef.value._show()
	}
	//置为已读
	async function handleSelectRead(index) {
		if (e.length == 0) return
		let selectList = list.value.filter(item => item.checked);
		let checkes = selectList.map(item => item.id);
		if (checkes.length == 0) {
			uni.showToast({
				title: '请选择数据',
				icon: 'none'
			});
			return;
		}
		const ids = checkes.join(',');
		try {
			uni.showLoading({
				title: '操作中...',
				mask: true
			});
			const res = await postFormAction(url.setReaded, {
				ids: ids,
				emailId: queryParam.value.emailId,
				isReaded: e[0].value
			});
			uni.showToast({
				title: res.msg,
				icon: 'none'
			});
			_handleRefresh();
		} catch (e) {
			uni.hideLoading()
		} finally {
			uni.hideLoading()
		}
	}
	//移动
	async function handleSelectMove(e) {
		console.log("e", e)
		if (e.length == 0) return
		let selectList = list.value.filter(item => item.checked);
		let checkes = selectList.map(item => item.id);
		if (checkes.length == 0) {
			uni.showToast({
				title: '请选择数据',
				icon: 'none'
			});
			return;
		}
		const ids = checkes.join(',');
		try {
			const params = {
				emailId: queryParam.value.emailId,
				ids: ids,
				box: e[0].value,
			};
			uni.showLoading({
				title: '移动中...',
				mask: true
			});
			const res = await postFormAction(url.moveMail, params);
			console.log("res", res)
			uni.showToast({
				title: res.msg,
				icon: 'none'
			});
			_handleRefresh();
		} catch (e) {
			uni.hideLoading()
		} finally {
			uni.hideLoading()
		}
	}
	const showMoveRef = ref(null)

	function handleShowMove() {
		showMoveRef.value._show()
	}
	return {
		list,
		isChecked,
		moveOptions,
		readOptions,
		search,
		_handleRefresh,
		_handleLook,
		_handleEdit,
		_handleTransmit,
		_handleDelete,
		_handleSelectAll,
		_handleCancel,
		handleDelete,
		_handleDeleteBatch,
		handleSelectRead,
		handleShowRead,
		showReadRef,
		handleSelectMove,
		showMoveRef,
		handleShowMove,
		emailInfo,
		queryParam
	}
}